package entity;

import java.util.HashMap;
import java.util.Map;

public class MetaData{
    //不写getter方法防止逃逸引用
    private Map<String,Object> meta;
    public MetaData(int capacity){
        this.meta=new HashMap<>(capacity);
    }
    public MetaData(){
        this.meta=new HashMap<>();
    }

    public Object get(String key){
        return meta.get(key);
    }

    public void del(String key){
        meta.remove(key);
    }

    public void put(String key,Object val){
        meta.put(key,val);
    }

    public String keys(String pattern){
        StringBuilder sb=new StringBuilder();
        int count=0;
        if (pattern.equals("*")){
            //全量匹配
            for (String key : meta.keySet()) {
                appendDataLine(key,sb,count);
            }
        }else if (pattern.endsWith("*")){
            //前缀匹配
            pattern=pattern.substring(0,pattern.length()-1);
            for (String key : meta.keySet()) {
                if (key.startsWith(pattern))
                    appendDataLine(key,sb,count);
            }
        }else {
            //唯一匹配
            Object o = meta.get(pattern);
            if (o!=null)
                appendDataLine(pattern,sb,count);
        }
        return sb.length()!=0?sb.substring(0,sb.length()-1): Result.ListEmpty();
    }

    public static void appendDataLine(String key,StringBuilder sb,int count){
        sb.append("(").append(++count).append("):").append(key).append("\n");
    }
}
